package com.efounder.chat.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class NewFriendsDBManager {
    private SQLiteDatabase db;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
    private int loginUserId;

    public NewFriendsDBManager() {
        try {
            this.loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID, "0")).intValue();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        this.db = GetDBHelper.getInstance().getDb();
    }

    /**
     * 插入或更新好友请求
     *
     * @param user
     * @return
     */
    public long insertOrUpdate(User user) {
        ContentValues values = getNewFriendsContentValues(user);
        return this.db.insertWithOnConflict("newfriend", null, values, SQLiteDatabase.CONFLICT_REPLACE);

    }

    /**
     * 插入或更新好友请求
     *
     * @param users
     */
    public void insertOrUpdate(List<User> users) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = users.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            insertOrUpdate(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 通过id查询好友请求
     *
     * @param id
     * @return
     */
    public User queryById(int id, int loginUserId) {
        String sql = "select * from NEWFRIEND,user where newfriend.userId=" + id + "  and user.userId=" + id + " and NEWFRIEND.loginUserId =" + loginUserId + " and NEWFRIEND.enable =1 ;";
        List<?> list = query(sql);
        return ((list.size() == 0) ? null : (User) list.get(0));

    }

    /**
     * 查询所有好友请求（分页）
     *
     * @return
     */
    public List<User> queryAllNewFriends(int loadedCount) {
        String sql = "select * from newfriend,user where newfriend.enable =1 and user.userId = " +
                "newFriend.userId and newfriend.loginUserId =" + loginUserId + " order by  newfriend.state asc, newfriend.time desc" +
                " Limit 20 offset " + loadedCount + ";";
        List<User> list = query(sql);
        return list;

    }

    /**
     * 查询所有好友请求未读数量
     *
     * @return
     */
    public int queryAllNewFriendsUnRead() {
        int count = 0;
        String sql = "select count(*) as count from newfriend where isread = 0 and newfriend.loginUserId =" + loginUserId + ";";
        Cursor cursor = this.db.rawQuery(sql, null);

        while (cursor.moveToNext()) {
            count = cursor.getInt(cursor.getColumnIndex("count"));
        }

        cursor.close();
        return count;

    }

    /**
     * 所有好友请求未读变为已读
     *
     * @return
     */
    public void updateAllNewFriendsSetIsRead() {
        int count = 0;
        String sql = "update  newfriend  set  isread = 1 where newfriend.loginUserId =" + loginUserId + ";";
        db.execSQL(sql);

    }

    /**
     * 更新好友请求(单个)
     *
     * @param user
     * @return
     */
    public int update(User user) {
        ContentValues values = getNewFriendsContentValues(user);
        String whereClause = "userId=? and loginUserId = ?";
        String[] whereArgs = {String.valueOf(user.getId()), String.valueOf(user.getLoginUserId())};
        return this.db.update("NEWFRIEND", values, whereClause, whereArgs);
    }

    /**
     * 更新好友请求(单个)
     *
     * @param
     * @return
     */
    public int delete(int userId) {
        return this.db.delete("NEWFRIEND", "userId=?", new String[]{userId + ""});
    }

    /**
     * 更新好友请求(list)
     *
     * @param list
     * @return
     */
    public void update(List<User> list) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = list.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            update(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 删除好友请求（单个）
     *
     * @param user
     * @return
     */
    public void delete(User user) {

        this.db.execSQL("update newfriend set enable=0 where userId =" + user.getId() +
                " and loginUserId =" + user.getLoginUserId() + ";");
    }


    /**
     * 删除好友请求（多个）
     *
     * @param userList
     */
    public void delete(List<User> userList) {
        this.db.beginTransaction();
        for (Iterator<User> localIterator = userList.iterator(); localIterator
                .hasNext(); ) {
            User user = (User) localIterator.next();
            delete(user);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public List<User> query(String sql) {
        return query(sql, null);
    }

    public List<User> query(String sql, String[] selectionArgs) {
        List<User> list = new ArrayList<User>();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);
        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("userId")));
            user.setLoginUserId(cursor.getInt(cursor.getColumnIndex("loginUserId")));
            user.setState(cursor.getInt(cursor.getColumnIndex("state")));

            user.setName(cursor.getString(cursor.getColumnIndex("name")));
            user.setNickName(cursor.getString(cursor.getColumnIndex("nickName")));
            user.setSex(cursor.getString(cursor.getColumnIndex("sex")));
            user.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            user.setMobilePhone(cursor.getString(cursor
                    .getColumnIndex("mobilephone")));
            user.setAvatar(cursor.getString(cursor.getColumnIndex("avatar")));
            user.setSigNature(cursor.getString(cursor.getColumnIndex("sigNature")));
            user.setEmail(cursor.getString(cursor.getColumnIndex("email")));
            user.setDeptId(cursor.getInt(cursor.getColumnIndex("deptId")));
            user.setType(cursor.getInt(cursor.getColumnIndex("type")));
            user.setIsRead(cursor.getInt(cursor.getColumnIndex("isRead")) == 1 ? true : false);
            user.setLeaveMessage(cursor.getString(cursor.getColumnIndex("leave_message")));

            try {
                Date date = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("time")));
                user.setTime(date.getTime());
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }

            list.add(user);
        }

        cursor.close();
        return list;
    }

    private ContentValues getNewFriendsContentValues(User user) {
        ContentValues values = new ContentValues();
        values.put("userId", user.getId());
        values.put("loginUserId", user.getLoginUserId());
        values.put("state", user.getState());
        values.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS",
                Locale.getDefault()).format(new Date(user.getTime())));
        values.put("isRead", user.getIsRead() == true ? 1 : 0);
        values.put("leave_message", user.getLeaveMessage() == null ? "" : user.getLeaveMessage());
        values.put("enable", 1);
        return values;
    }


    /**
     * 关闭数据库
     */
    public void close() {
        this.db.close();
    }
}
